package cn.xfdzx.android.apps.shop.activity.myshop.bluedevic;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Set;

import cn.xfdzx.android.apps.shop.R;
import cn.xfdzx.android.apps.shop.adapter.BlueDevicListAdapter;
import cn.xfdzx.android.apps.shop.adapter.MyFollow_RetailAdapter;
import cn.xfdzx.android.apps.shop.adapter.MyFollow_XFDAdapter;
import cn.xfdzx.android.apps.shop.apps.Constants;
import cn.xfdzx.android.apps.shop.base.BaseMvpActivity;
import cn.xfdzx.android.apps.shop.bean.MyFollowBean;
import cn.xfdzx.android.apps.shop.contract.MyFollowContract;
import cn.xfdzx.android.apps.shop.presenter.MyFollowPresenter;
import cn.xfdzx.android.apps.shop.util.EmptyUtil;
import cn.xfdzx.android.apps.shop.util.ProgressDialog;
import cn.xfdzx.android.apps.shop.util.StatusBarUtil;
import cn.xfdzx.android.apps.shop.util.Utils;
import cn.xfdzx.android.apps.shop.util.UtilsData;

import static android.provider.Settings.Global.DEVICE_NAME;

/*
/* 打印设置页面
 */
public class PrintSetActivity extends BaseMvpActivity<MyFollowPresenter> implements MyFollowContract.View, View.OnClickListener {
    private ImageView ivBack;      //标题栏-左边按钮

    private MyFollow_RetailAdapter myFollowRetailAdapter;//零售关注列表
    private List<MyFollowBean.DataBean.RetailBean> retail;
    private MyFollow_XFDAdapter myFollowXfdAdapter;
    private List<MyFollowBean.DataBean.WholesaleBean> wholesale;
    private RecyclerView rv_paired_devices,rv_new_devices;//已配对列表和可用列表
    private Dialog dialog;//确认清除弹窗
    private RelativeLayout.LayoutParams item_bar;
    private LinearLayout llState;
    private BlueDevicListAdapter blueDevicListAdapter,newDevicListAdapter;
    private ArrayList<BluetoothDevice> devicList;
    // Return Intent extra
    public static String EXTRA_DEVICE_ADDRESS = "device_address";
    public static String EXTRA_DEVICE_NAME = "device_name";
    // Name of the connected device
    private String mConnectedDeviceName = null;
    // Member fields
    private BluetoothAdapter mBtAdapter;
    // Member object for the services
    private BluetoothService mService = null;
    // Message types sent from the BluetoothService Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final int MESSAGE_CONNECTION_LOST = 6;
    public static final int MESSAGE_UNABLE_CONNECT = 7;

    // Intent request codes
    private static final int REQUEST_CONNECT_DEVICE = 1;
    private static final int REQUEST_ENABLE_BT = 2;
    private static final int REQUEST_CHOSE_BMP = 3;
    private static final int REQUEST_CAMER = 4;

    //QRcode
    private static final int QR_WIDTH = 350;
    private static final int QR_HEIGHT = 350;

    // Key names received from the BluetoothService Handler
    public static final String DEVICE_NAME = "device_name";
    public static final String TOAST = "toast";
    private int currentPosition;//当前角标
    private BluetoothDevice currentBluetoothDevice;//当前连接
    @Override
    public int getLayoutId() {
        return R.layout.activity_bluetooth;
    }

    @Override
    public void onStart() {
        super.onStart();

        // If Bluetooth is not on, request that it be enabled.
        // setupChat() will then be called during onActivityResult
        if (!mBtAdapter.isEnabled()) {
            Intent enableIntent = new Intent(
                    BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
            // Otherwise, setup the session
        }else {
            if (mService == null)
                KeyListenerInit();//监听
        }
    }

    private void initHigh() {
        item_bar = (RelativeLayout.LayoutParams) llState.getLayoutParams();
        item_bar.height = StatusBarUtil.getStatusBarHeight(this);
        llState.setLayoutParams(item_bar);

    }
    @Override
    public void initView() {

        // Get the local Bluetooth adapter
        mBtAdapter = BluetoothAdapter.getDefaultAdapter();
        // If the adapter is null, then Bluetooth is not supported
        if (mBtAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available",
                    Toast.LENGTH_LONG).show();
            finish();
        }

        mPresenter = new MyFollowPresenter();
        mPresenter.attachView(this);

        rv_paired_devices = findViewById(R.id.paired_devices);
        rv_new_devices = findViewById(R.id.new_devices);
        llState = findViewById(R.id.ll_state);
        ivBack = findViewById(R.id.iv_back);
        ivBack.setOnClickListener(this);

      //  initRecycle();
        initHigh();
        dialog = Utils.addDialog(this, R.layout.dialog, R.string.confirmclearfollow, R.string.confirm, new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                dialog.dismiss();
            }
        });
    }

    private void initRecycle() {
        // Register for broadcasts when a device is discovered
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        this.registerReceiver(mReceiver, filter);

        // Register for broadcasts when discovery has finished
        filter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        this.registerReceiver(mReceiver, filter);

        rv_paired_devices.setLayoutManager(new LinearLayoutManager(this));
        rv_new_devices.setLayoutManager(new LinearLayoutManager(this));

        /*已配对设备*/
        blueDevicListAdapter = new BlueDevicListAdapter(devicList);
        rv_paired_devices.setAdapter(blueDevicListAdapter);
        blueDevicListAdapter.setOnItemConnectionListener(new BlueDevicListAdapter.OnItemOnClickListener() {
            @Override
            public void onItemConnectionClick(BluetoothDevice itemDate, int position) {
                // Cancel discovery because it's costly and we're about to connect
                mBtAdapter.cancelDiscovery();
                currentPosition  = position;
                currentBluetoothDevice  = itemDate;

                //如果是连接状态
                if (mService.getState() == BluetoothService.STATE_CONNECTED){
                    //如果连接的名称和点击的名称是一个，跳设置页面
                    if (itemDate.getName().equals(UtilsData.getPreference(PrintSetActivity.this,
                            "login").getString("bluedevic"))){
                        Intent intent = new Intent(PrintSetActivity.this, PrintBlueDevicSetActivity.class);
                        intent.putExtra(EXTRA_DEVICE_NAME, UtilsData.getPreference(PrintSetActivity.this,
                                "login").getString("bluedevic"));

                        startActivity(intent);
                        finish();
                    }else {
                        mService.stop();
                        if (BluetoothAdapter.checkBluetoothAddress(itemDate.getAddress())) {
                            BluetoothDevice device = mBtAdapter
                                    .getRemoteDevice(itemDate.getAddress());
                            // Attempt to connect to the device
                            mService.connect(device);

                            showLoading();
                        }
                    }

                }else {
                    mService.stop();
                    if (BluetoothAdapter.checkBluetoothAddress(itemDate.getAddress())) {
                        BluetoothDevice device = mBtAdapter
                                .getRemoteDevice(itemDate.getAddress());
                        // Attempt to connect to the device
                        mService.connect(device);

                        showLoading();
                    }
                }

//                if (currentPosition == position){
//                    checkCollectionState(itemDate);
//                }else {
//                   // mService.stop();
//                    checkCollectionState(itemDate);
//                }

            }
        });

        /*其他可用设备*/
        newDevicListAdapter = new BlueDevicListAdapter(devicList);
        rv_new_devices.setAdapter(newDevicListAdapter);
        newDevicListAdapter.setOnItemConnectionListener(new BlueDevicListAdapter.OnItemOnClickListener() {
            @Override
            public void onItemConnectionClick(BluetoothDevice itemDate, int position) {
                // Cancel discovery because it's costly and we're about to connect
                mBtAdapter.cancelDiscovery();

                currentPosition  = position;
                currentBluetoothDevice  = itemDate;
                if (BluetoothAdapter.checkBluetoothAddress(itemDate.getAddress())) {
                    BluetoothDevice device = mBtAdapter
                            .getRemoteDevice(itemDate.getAddress());
                    // Attempt to connect to the device
                    mService.connect(device);
                    showLoading();
                }
            }
        });


        doDiscovery();

        // Get a set of currently paired devices
        Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();

        // If there are paired devices, add each one to the ArrayAdapter
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
            for (BluetoothDevice device : pairedDevices) {
                blueDevicListAdapter.addData(device);
            }
        } else {
//            String noDevices = getResources().getText(R.string.none_paired).toString();
//            mPairedDevicesArrayAdapter.add(noDevices);
        }

        //如果当前蓝牙打印机处于连接状态
        if (mService.getState()==BluetoothService.STATE_CONNECTED){
            blueDevicListAdapter.setCollection( UtilsData.getPreference(PrintSetActivity.this,
                    "login").getString("bluedevic"));
        }

     }

    // The BroadcastReceiver that listens for discovered devices and
    // changes the title when discovery is finished
    private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            // When discovery finds a device
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                // If it's already paired, skip it, because it's been listed already
                if (device.getBondState() != BluetoothDevice.BOND_BONDED) {
                    newDevicListAdapter.addData(device);
                }
                // When discovery is finished, change the Activity title
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                setProgressBarIndeterminateVisibility(false);
               // setTitle(R.string.select_device);
//                if (mNewDevicesArrayAdapter.getCount() == 0) {
//                    String noDevices = getResources().getText(R.string.none_found).toString();
//                    mNewDevicesArrayAdapter.add(noDevices);
//                }
            }
        }
    };


    @Override
    protected void onResume() {
        super.onResume();
        if (null!=mBtAdapter)
        mBtAdapter.startDiscovery();
//        page = 1;
//        mPresenter.getFollowList(true,true,limit,page);
    }

    @Override
    public void finishRefresh() {
        //mRefreshLayout.finishRefresh(true);//刷新完成
    }

    @Override
    public void finishLoadMore() {
        //mRefreshLayout.finishLoadMore(true);//加载完成
    }

    @Override
    public void showLoading() {
        if (!ProgressDialog.getInstance().materialDialog.isShowing()) {
            ProgressDialog.getInstance().show(this);
        }
    }

    @Override
    public void hideLoading() {
        ProgressDialog.getInstance().dismiss();
    }

    @Override
    public void onError(Throwable throwable) {

    }

    @Override
    public void getFollowListSuccess(MyFollowBean bean) {
        if (bean.getStatus() == Constants.SUCCESS_CODE) {

        }else {
            Toast.makeText(this, bean.getMsg(), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void getDeleteFollowSuccess(MyFollowBean bean) {
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (dialog.isShowing()) {
            dialog.dismiss();

        }
        if (EmptyUtil.isNotEmpty(mPresenter))
        mPresenter.detachView();
        // Make sure we're not doing discovery anymore
        if (mBtAdapter != null) {
            mBtAdapter.cancelDiscovery();
        }

        // Unregister broadcast listeners
        try {
            this.unregisterReceiver(mReceiver);
        }catch (Exception e){

        }
        super.onDestroy();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:    //返回按钮点击
                finish();
                break;

        }
    }

    /**
     * Start device discover with the BluetoothAdapter
     */
    private void doDiscovery() {

        // Indicate scanning in the title
        setProgressBarIndeterminateVisibility(true);
       // setTitle(R.string.scanning);

        // Turn on sub-title for new devices
        //findViewById(R.id.title_new_devices).setVisibility(View.VISIBLE);

        // If we're already discovering, stop it
        if (mBtAdapter.isDiscovering()) {
            mBtAdapter.cancelDiscovery();
        }

        //mNewDevicesArrayAdapter.clear();//20160617
        //  mPairedDevicesArrayAdapter.clear();//20160617
        // Request discover from BluetoothAdapter
        mBtAdapter.startDiscovery();
    }

    /****************************************************************************************************/
    @SuppressLint("HandlerLeak")
    private final Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.e("handleMessage","11111");
            switch (msg.what) {
                case MESSAGE_STATE_CHANGE:
                    Log.e("handleMessage","2222");
                    switch (msg.arg1) {
                        case BluetoothService.STATE_CONNECTED://连接成功
                            hideLoading();
                            Log.e("handleMessage","333");
                            Log.e("BluetoothService","连接成功"+"==="+currentBluetoothDevice.getName());
                            //保存连接的名称，用于关闭页面重新打开显示连接状态
                            UtilsData.getPreference(PrintSetActivity.this, "login").put("bluedevic",currentBluetoothDevice.getName());
                            //blueDevicListAdapter.setSel(currentPosition);
                            blueDevicListAdapter.setCollection(UtilsData.getPreference(PrintSetActivity.this, "login").getString("bluedevic"));
                            Intent intent = new Intent(PrintSetActivity.this, PrintBlueDevicSetActivity.class);
                            if (EmptyUtil.isNotEmpty(currentBluetoothDevice.getName())){
                                intent.putExtra(EXTRA_DEVICE_NAME, currentBluetoothDevice.getName());
                            }else {
                                intent.putExtra(EXTRA_DEVICE_NAME, currentBluetoothDevice.getAddress());
                            }

                            startActivity(intent);
                            finish();
                            break;
                        case BluetoothService.STATE_CONNECTING://连接中
                            Log.e("BluetoothService","连接中");
                            Log.e("handleMessage","444");
                            break;
                        case BluetoothService.STATE_LISTEN:
                        case BluetoothService.STATE_NONE://未连接
                            hideLoading();
                            Log.e("BluetoothService","未连接");
                            Log.e("handleMessage","5555");
//                            Toast.makeText(getApplicationContext(),
//                                    "连接失败请检查蓝牙设备" + mConnectedDeviceName,
//                                    Toast.LENGTH_SHORT).show();
                            break;
                    }
                    break;
                case MESSAGE_WRITE:
                    Log.e("BluetoothService","MESSAGE_WRITE");
                    Log.e("handleMessage","666");
                    break;
                case MESSAGE_READ:
                    Log.e("BluetoothService","MESSAGE_READ");
                    Log.e("handleMessage","7777");
                    break;
                case MESSAGE_DEVICE_NAME:
                    hideLoading();
                    Log.e("handleMessage","888");
                    // save the connected device's name
                    mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
//                    Toast.makeText(getApplicationContext(),
//                            "连接蓝牙" + mConnectedDeviceName,
//                            Toast.LENGTH_SHORT).show();
                    break;
                case MESSAGE_TOAST:
                    Log.e("MESSAGE_TOAST","MESSAGE_TOAST");
                    Log.e("handleMessage","999");

                    hideLoading();
                    Toast.makeText(getApplicationContext(),
                            msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
                            .show();
                    break;
                case MESSAGE_CONNECTION_LOST:    //蓝牙已断开连接
                    hideLoading();
                    Log.e("handleMessage","10-10-10");
//                    Toast.makeText(getApplicationContext(), "蓝牙已断开连接",
//                            Toast.LENGTH_SHORT).show();

                    break;
                case MESSAGE_UNABLE_CONNECT:     //无法连接设备
                    hideLoading();
                    Log.e("handleMessage","11-11-11-11");
                    Toast.makeText(getApplicationContext(), "无法连接设备，请重试",
                            Toast.LENGTH_SHORT).show();
                    break;
            }
        }
    };

    @SuppressLint("MissingSuperCall")
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_ENABLE_BT:{
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a session
                    KeyListenerInit();
                } else {
                    // User did not enable Bluetooth or an error occured
                    Toast.makeText(this, "蓝牙无法启动，页面关闭",
                            Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            }
        }
    }

    private void KeyListenerInit() {
        mService = BluetoothService.getInstance(this, mHandler);

        Log.e("mService",mService.getState()+"---");
        initRecycle();
    }
}
